package com.kenyi.co.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.google.gson.Gson;
import com.kenyi.co.GlideApp;
import com.kenyi.co.MainActivity;
import com.kenyi.co.R;
import com.kenyi.co.common.bean.Netbean;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.common.ui.WebActivity;
import com.kenyi.co.common.utils.RouteUtils;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.me.ui.MeFavActivity;
import com.kenyi.co.ui.model.FirstScreenBean;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

import static com.kenyi.co.common.utils.RouteUtils.getFav;
import static com.kenyi.co.utils.CommonUtils.isFastClick;


/**
 * 启动页
 */
public class StartActivity extends BaseActivity {
    private static final String TAG = "StartActivity";
    private ImageView imageView2, imageView, iv_start_pic2;
    private TextView tv_start_skip;
    private LinearLayout go;
    private Timer mTimer;
    private TimerTask mTimerTask;

    private boolean goflag = true;
    //大淘客的广告
    private FirstScreenBean packlist;
    private String nvimgurl;
    private int code = 1;
    private int duration = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        setContentView(R.layout.strart2);
        SharepUtils.setString_info(StartActivity.this, "1", SharepUtils.VIDEO_ONE);
        initView();
        getNvimg();
        getOutip();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        timeUtils(1);
    }

    /**
     * 倒计时的管理
     */
    public void timeUtils(final int type) {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    updateUIText(type);
                }
            };

            @Override
            public void run() {
                runOnUiThread(updateUI);
            }
        };
        mTimer.schedule(mTimerTask, 0, 1000);
    }

    /**
     * 处理文本的显示
     */
    public void updateUIText(int type) {

        switch (type) {
            case 1:
                duration--;

                if (duration <= 0) {
                    gotoMainActivity();
                } else {
                    tv_start_skip.setText(duration + "跳过");
                }

                break;


            default:
                break;
        }


    }

    private void initView() {
        //全屏广告布局
        imageView = (ImageView) findViewById(R.id.iv_start_pho);
        tv_start_skip = findViewById(R.id.tv_start_skip);
        tv_start_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoMainActivity();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart("启动页");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        MobclickAgent.onPageEnd("启动页");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Util.isOnMainThread()) {
            Glide.with(getApplicationContext()).pauseRequests();
        }

    }


    @Override
    protected void onStart() {
        super.onStart();


    }


    /*
     * 0、返回数据
     *
     *
     */
    public void gotoMainActivity() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if(!goflag){
            return;
        }
        goflag = false;
        if ("1".equals(SharepUtils.getString_info(StartActivity.this, SharepUtils.USER_LOGIN_ONE))) {
            Intent intent2 = new Intent();
            intent2.setClass(StartActivity.this, MainActivity.class);
            startActivity(intent2);
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        } else {
            Intent intent2 = new Intent();
            intent2.setClass(StartActivity.this, MeFavActivity.class);
            Bundle bundlelogin = new Bundle();
            bundlelogin.putString("isfinish", "1");
            intent2.putExtras(bundlelogin);
            startActivity(intent2);
        }

        finish();
    }

    public void gotowebview(String url, String title) {
        if (url.length() > 6) {

            Map<String, String> params = new HashMap<>();


            params.put("title", "");
            params.put("articleId", "");
            params.put("advid", packlist.getDatas().get(0).getId());
            params.put("adPosition", 6 + "");
            params.put("pageName", "StartActivity");
            params.put("carrierName", CommonUtils.getOperator(StartActivity.this));
            getFav(StartActivity.this,params );

            Intent intentgo1 = new Intent(StartActivity.this, WebActivity.class);
            Bundle bundle1 = new Bundle();
            bundle1.putString("title", title);
            bundle1.putString("is_main", "1");
            bundle1.putString("URL", url);
            intentgo1.putExtras(bundle1);
            startActivity(intentgo1);
            finish();
        }

    }


    /**
     * 获取大淘客图片的资源
     */
    public void getNvimg() {

        Map<String, String> params = new HashMap<>();
        params.put("version", "2");
        Map<String, String> headers = new HashMap<>();
        headers.put("APP-Key", "APP-Secret");
        String url = NetConfig.AD_FIRSTSCREEN;
        OkHttpUtils.get()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        packlist = gson.fromJson(response, FirstScreenBean.class);
                        code = packlist.getCode();
                        if (code == 200) {
                            if (packlist.getDatas() != null && packlist.getDatas().size() > 0) {
                                String img = packlist.getDatas().get(0).getImgs().get(0);
                                nvimgurl = packlist.getDatas().get(0).getUrl();//网页地址

                                imageView.setVisibility(View.VISIBLE);
                                duration = packlist.getDatas().get(0).getDuration();
                                tv_start_skip.setText(duration + "跳过");
                                if (Util.isOnMainThread()) {
                                    GlideApp.with(StartActivity.this)
                                            .load(img)
                                            .into(imageView);
                                    imageView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (mTimer != null) {
                                                mTimer.cancel();
                                                mTimer = null;
                                            }
                                            if(isFastClick()){
                                                gotowebview(nvimgurl, "");

                                            }

                                        }
                                    });
                                }
                                tv_start_skip.setVisibility(View.VISIBLE);
                            } else {
                                tv_start_skip.setVisibility(View.GONE);
                            }
                            timeUtils(1);


                        }
                    }
                });
    }

    /**
     * 获取偏好
     */
    public void getOutip() {

        Map<String, String> params = new HashMap<>();

        params.put("page", "");
        String url = "http://pv.sohu.com/cityjson";

        OkHttpUtils.get()
                .url(url)
                .params(params)

                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        int satrtIndex = response.indexOf("{");//包含[
                        int endIndex = response.indexOf("}");//包含]
                        String response1 = response.substring(satrtIndex, endIndex + 1);//包含[satrtIndex,endIndex)
                        Netbean packlist = gson.fromJson(response1, Netbean.class);

                        SharepUtils.setString_info(StartActivity.this, packlist.getCip(), SharepUtils.OUT_IP);
                    }


                });

    }

}
